import { apiGetMenuList } from 'js/api'
import { session } from 'js/util'

export default {
  state: {
    menuList: {},
    oneMenuList: [] // 一级菜单
  },
  getters: {
    menuList: state => state.menuList,
    oneMenuList: state => state.oneMenuList
  },
  actions: {
    /**
     * 获取该用户权限下的所有菜单列表
     */
    fetchMenuList({ state }, token) {
      // 若已调用接口，则不再重复调用
      state.oneMenuList = []
      // if (state.oneMenuList.length > 0) return
      apiGetMenuList(token).then(data => {
        state.menuList = data.data.menu || {} // 获取全部菜单
        if (state.menuList && state.menuList.length > 0) {
          state.menuList.forEach((oneMenu, oneIndex) => {
            state.oneMenuList.push(oneMenu)
          })
        }
      })
    },
    /**
     * 重新获取当前的菜单数据
     */
    resetMenuList({ state }, token) {
      let curMenu = []
      const oldMenuCurIndex = session.get('curMenuIndex') || '' // 当期存储的旧数据
      apiGetMenuList(token).then(data => {
        state.menuList = data.data.menu || {} // 获取全部菜单
        if (state.menuList && state.menuList.length > 0) {
          state.menuList.forEach((oneMenu, oneIndex) => {
            if (oldMenuCurIndex == oneIndex) {
              oneMenu.twoList.forEach(two => {
                curMenu.push(two)
                session.set('curMenu', curMenu)
              })
            }
          })
        }
      })
    }
  },
  mutations: {
    /**
     * 重新获取当前的菜单数据
     */
    resetMenuList() {
      const oldMenuCurIndex = session.get('curMenuIndex') || '' // 当期存储的旧数据
      apiGetMenuList(token).then(data => {
        state.menuList = data.data.menu || {} // 获取全部菜单
        if (state.menuList && state.menuList.length > 0) {
          state.menuList.forEach((oneMenu, oneIndex) => {
            if (oldMenuCurIndex == index) {
              session.remove('curMenu')
              state.oneMenuList.push(oneMenu)
            }
          })
        }
      })
    }
  }
}